/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="openatc-gis" id="openatc-gis">
    <div id="map"></div>
    <div class="footer-right">
      {{this.$t('openatc.devicemanager.longitude') }} {{ lngLat.lng }}
      {{this.$t('openatc.devicemanager.latitude') }}  {{ lngLat.lat }}
      {{this.$t('openatc.devicemanager.layerLevel') }} {{ zoom }}
    </div>
    <div v-if="isTool" class="tools">
      <el-button @click="handMeasureDistance" type="text">{{this.$t('openatc.devicemanager.tools') }}</el-button>
    </div>
  </div>
</template>
<script>
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
// 绘制
import 'leaflet-draw'
import './store/MoudeTips'
import './store/MoudeTips.css'
import 'leaflet-draw/dist/leaflet.draw.css'
import 'leaflet-measure-path/leaflet-measure-path.css'
import 'leaflet-measure-path/leaflet-measure-path.js'
import 'leaflet.chinatmsproviders'
import 'leaflet.vectorgrid'
import { SystemconfigApi } from '../../api/systemconfig.js'
import { getLanguage } from '../../utils/auth'
export default {
  data () {
    return {
      mapType: '2D',
      lngLat: {
        lng: '0.00000000',
        lat: '0.00000000'
      },
      zoom: 12,
      minZoom: 3,
      maxZoom: 21,
      points: [],
      color: 'red',
      layers: L.layerGroup(),
      polyline: null,
      polylineGroup: [],
      marker: null,
      deviceOnlineIcon: require('../../assets/gis/deviceonline.png'),
      markerGroup: [],
      center: [31.23636, 121.53413],
      // gis: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      // gisNormal: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      // gisStatellite: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      gis: 'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
      gisNormal: 'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
      gisNormalAnnotationZh: '', // 中文注记
      gisNormalAnnotationEn: '', // 英文注记
      gisStatellite: 'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
      gisBoundLeftTop: [],
      gisBoundRightBottom: [],
      gisNormal_mapbox: '',
      gisStatellite_mapbox: '',
      gisNormalAnnotationZh_mapbox: '', // mapbox中文注记
      gisNormalAnnotationEn_mapbox: '', // mapbox英文注记
      tianDiTuKey: '3bfb2112c0920226f0592fd64cd2c70d'
    }
  },
  props: {
    isTool: {
      type: Boolean,
      default: false
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    async init () {
      await this.getGisConfig()
      await this.initMap()
      await this.addMapEvent()
      this.$emit('onMapInit', this.map)
    },
    initMap () {
      let _this = this
      let map = _this.loadLocalMapType()
      if (this.gisBoundLeftTop && this.gisBoundLeftTop.length > 1 && this.gisBoundRightBottom.length > 1) {
        let corner1 = L.latLng(this.gisBoundLeftTop[0], this.gisBoundLeftTop[1])
        let corner2 = L.latLng(this.gisBoundRightBottom[0], this.gisBoundRightBottom[1])
        let bounds = L.latLngBounds(corner1, corner2)
        map.setMaxBounds(bounds)
      }
      _this.map = map// data上需要挂载
      window.map = map
    },
    addMapEvent () {
      let _this = this
      _this.map.on('mousemove', function (e) {
        _this.lngLat.lng = _this.computedLngLat(String(e.latlng.lng))
        _this.lngLat.lat = _this.computedLngLat(String(e.latlng.lat))
      })
      _this.map.on('zoomend', function (e) {
        _this.zoom = _this.map.getZoom()
      })
      // _this.map.on('click', this.click).on('dblclick', this.dblclick)
    },
    // 计算经纬度
    computedLngLat (num) {
      var text = ''
      var index = num.indexOf('.')
      if (index !== -1) {
        text = num.substring(0, index + 9)
      } else {
        text = num
      }
      return text
    },
     inits () {
      const _this = this
      // _this.points = []
      // _this.polyline = null
      // _this.marker = null
      _this.layers.addTo(_this.map) // Ensure layers are on the map
    },
    click (e) {
      const _this = this
      _this.map.doubleClickZoom.disable()
      // Add point information
      _this.points.push(e.latlng)
      // Add mousemove listener
      _this.map.on('mousemove', _this.mousemove)
    },
    mousemove (e) {
      const _this = this
      _this.points.push(e.latlng)
      if (_this.polyline) {
        _this.map.removeLayer(_this.polyline)
      }
      _this.polyline = L.polyline(_this.points, {
        showMeasurements: true,
        color: _this.color
      })
      _this.polyline.addTo(_this.layers)
      _this.layers.addTo(_this.map)
      _this.points.pop() // Remove the latest point for visual purposes
    },
    dblclick (e) {
      const _this = this
      _this.mouseTips.hide()
      _this.polylineGroup.push(this.polyline)
      _this.close(e.latlng, this.polyline)
      _this.map.off('click', _this.click).off('mousemove', _this.mousemove).off('dblclick', _this.dblclick)
      this.points = []
      this.polyline = null
      this.markerGroup = []
    },
    close (latlng, polyline) {
      const _this = this
      // let deleteIcon = L.icon({
      //     iconUrl: 'x',
      //     iconSize: [20, 20], // 图标大小
      //     iconAnchor: [14, 20] // 图标偏移量，否则无法居住显示
      //   })
          // 创建自定义图标，使用 divIcon 以便于直接使用字符
      let deleteIcon = L.divIcon({
        className: 'custom-delete-icon',
        html: '<span style="color:red; font-size:20px;">x</span>',
        iconSize: [20, 20], // 图标大小
        iconAnchor: [10, 20] // 图标偏移量，居中显示
      })
      let marker = L.marker(latlng, { icon: deleteIcon }).addTo(_this.map).on('click', function (e) {
        if (polyline) {
          _this.map.removeLayer(polyline)
        }
        if (marker) {
          marker.remove()
        }
      })
      this.markerGroup.push(marker)
    },
      // startMeasurement () {
      //   // 鼠标绘制提示
      //   this.mouseTips.addTo(this.map).show()
      //   this.inits()
      // },
    handMeasureDistance () {
      const _this = this
      if (_this.mouseTips) {
        _this.map.removeControl(_this.mouseTips)
      }
      _this.mouseTips = L.control.mouseTips({
        show: true,
        message: '鼠标单击左键加点，双击结束'
      })
      _this.mouseTips.addTo(_this.map).show()
      _this.inits()
      this.map.on('click', this.click).on('dblclick', this.dblclick)
    },
    getVectorTileStyling () {
      let vectorTileStyling = {
        water: {
          fill: true,
          weight: 1,
          fillColor: '#06cccc',
          color: '#06cccc',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        admin: {
          weight: 1,
          fillColor: 'pink',
          color: 'pink',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        waterway: {
          weight: 1,
          fillColor: '#2375e0',
          color: '#2375e0',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        landcover: {
          fill: true,
          weight: 1,
          fillColor: '#53e033',
          color: '#53e033',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        landuse: {
          fill: true,
          weight: 1,
          fillColor: '#e5b404',
          color: '#e5b404',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        park: {
          fill: true,
          weight: 1,
          fillColor: '#84ea5b',
          color: '#84ea5b',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        boundary: {
          weight: 1,
          fillColor: '#c545d3',
          color: '#c545d3',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        aeroway: {
          weight: 1,
          fillColor: '#51aeb5',
          color: '#51aeb5',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        road: {
          weight: 1,
          fillColor: '#f2b648',
          color: '#f2b648',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        tunnel: {
          weight: 0.5,
          fillColor: '#f2b648',
          color: '#f2b648',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        bridge: {
          weight: 0.5,
          fillColor: '#f2b648',
          color: '#f2b648',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        transportation: {
          weight: 0.5,
          fillColor: '#f2b648',
          color: '#f2b648',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        transit: {
          weight: 0.5,
          fillColor: '#f2b648',
          color: '#f2b648',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        building: {
          fill: true,
          weight: 1,
          fillColor: '#2b2b2b',
          color: '#2b2b2b',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        water_name: {
          weight: 1,
          fillColor: '#022c5b',
          color: '#022c5b',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        transportation_name: {
          weight: 1,
          fillColor: '#bc6b38',
          color: '#bc6b38',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        place: {
          weight: 1,
          fillColor: '#f20e93',
          color: '#f20e93',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        housenumber: {
          weight: 1,
          fillColor: '#ef4c8b',
          color: '#ef4c8b',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        poi: {
          weight: 1,
          fillColor: '#3bb50a',
          color: '#3bb50a',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        earth: {
          fill: true,
          weight: 1,
          fillColor: '#c0c0c0',
          color: '#c0c0c0',
          fillOpacity: 0.2,
          opacity: 0.4
        },
        country_label: [],
        marine_label: [],
        state_label: [],
        place_label: [],
        waterway_label: [],
        poi_label: [],
        road_label: [],
        housenum_label: [],
        country_name: [],
        marine_name: [],
        state_name: [],
        place_name: [],
        waterway_name: [],
        poi_name: [],
        road_name: [],
        housenum_name: []
      }
      vectorTileStyling.buildings = vectorTileStyling.building
      vectorTileStyling.boundaries = vectorTileStyling.boundary
      vectorTileStyling.places = vectorTileStyling.place
      vectorTileStyling.pois = vectorTileStyling.poi
      vectorTileStyling.roads = vectorTileStyling.road
      return vectorTileStyling
    },
    loadLocalMapType () {
      // let mbUrl = 'https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw'

      let grayscale = L.tileLayer(this.gisNormal, {id: 'mapbox/light-v9'})

      // let grayscale = L.vectorGrid.protobuf('https://{s}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/{z}/{x}/{y}.vector.pbf?access_token={token}', {
      // let grayscale = L.vectorGrid.protobuf('http://192.168.13.113:55555/api/gis/rest/services/jxh/MapServer/tile/{z}/{y}/{x}.vector.pbf?access_token={token}', {
      if (this.gisNormal_mapbox) {
        let vectorTileStyling = this.getVectorTileStyling()
        grayscale = L.vectorGrid.protobuf('/api/gis/rest/services/sh/MapServer/tile/{z}/{y}/{x}', {
          rendererFactory: L.canvas.tile,
          vectorTileLayerStyles: vectorTileStyling,
          subdomains: 'abcd',
          token: 'pk.eyJ1IjoicmVwb2FsZXgwMDEiLCJhIjoiY2xndGJkcXduMDQxODNlcGR4cWlicmtzNSJ9.8bC2kaR5L0TMTvr43uY2TA'
        })
      }
      // 高德地图
      // let grayscale = L.tileLayer('http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', {
      //   attribution: '&copy; 高德地图',
      //   maxZoom: 15,
      //   minZoom: 10,
      //   subdomains: '1234'
      // })
      // 百度地图
      // let grayscale = L.tileLayer(
      //   'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}'
      // )
      let streets = L.tileLayer(this.gisStatellite, {id: 'mapbox/streets-v11'})

      // 注记
      const ciaZh = L.tileLayer(this.gisNormalAnnotationZh, {
        id: 'tianditu/ciaZh',
        zIndex: 1
      })
      const ciaEn = L.tileLayer(this.gisNormalAnnotationEn, {
        id: 'tianditu/ciaEn',
        zIndex: 1
      })

      let cia = ciaZh
      let language = getLanguage()
      if (language === 'en') {
        cia = ciaEn
      }

      // 加了注记图层的图组
      const annotationMap = L.layerGroup([grayscale, cia])

      let baseLayers = {
        '地图': annotationMap,
        '影像': streets
      }
      let overlayLayers = {}
      let map = L.map('map', {
        layers: [annotationMap],
        minZoom: this.minZoom,
        maxZoom: this.maxZoom,
        center: this.center,
        zoom: this.zoom,
        zoomControl: false,
        attributionControl: false,
        crs: L.CRS.EPSG3857,
        dragging: true,
        editMode: false,
        preferCanvas: true
      })
      let options = {
        position: 'bottomleft'
      }
      L.control.layers(baseLayers, overlayLayers, options).addTo(map)
      return map
    },
    loadMapType () {
      let normalm = L.tileLayer.chinaProvider('TianDiTu.Normal.Map', {
        key: this.tianDiTuKey,
        maxZoom: this.maxZoom,
        minZoom: this.minZoom
      })
      let normala = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', {
        key: this.tianDiTuKey,
        maxZoom: this.maxZoom,
        minZoom: this.minZoom
      })
      let imgm = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', {
        key: this.tianDiTuKey,
        maxZoom: this.maxZoom,
        minZoom: this.minZoom
      })
      let imga = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion', {
        key: this.tianDiTuKey,
        maxZoom: this.maxZoom,
        minZoom: this.minZoom
      })
      let normal = L.layerGroup([normalm, normala])
      let image = L.layerGroup([imgm, imga])
      let baseLayers = {
        '地图': normal,
        '影像': image
      }
      let overlayLayers = {}
      let map = L.map('map', {
        layers: [normal],
        minZoom: this.minZoom,
        maxZoom: this.maxZoom,
        center: this.center,
        zoom: this.zoom,
        zoomControl: false,
        attributionControl: false,
        crs: L.CRS.EPSG3857,
        dragging: true,
        editMode: false,
        preferCanvas: true
      })
      let options = {
        position: 'bottomleft'
      }
      L.control.layers(baseLayers, overlayLayers, options).addTo(map)
      return map
    },
    getGisConfig () {
      return new Promise((resolve, reject) => {
        let reqData = {
          module: 'gis',
          isValid: true
        }
        SystemconfigApi.GetSystemconfigList(reqData).then((data) => {
          let res = data.data
          if (!res.success) {
            console.log('datas:' + res)
            throw new Error('get gis error')
          } else {
            for (let config of data.data.data) {
              if (config['key'] === 'minZoom') {
                this.minZoom = Number(config['value'])
              }
              if (config['key'] === 'maxZoom') {
                this.maxZoom = Number(config['value'])
              }
              if (config['key'] === 'center') {
                let cen = config['value']
                let ss = cen.split(',')
                let s1 = ss[0].replace('[', '')
                let s2 = ss[1].replace(']', '').trim()
                this.center = [Number(s1), Number(s2)]
              }
              if (config['key'] === 'zoom') {
                this.zoom = Number(config['value'])
              }
              if (config['key'] === 'gisNormal') {
                this.gisNormal = config['value']
              }
              if (config['key'] === 'gisNormalAnnotationZh') {
                this.gisNormalAnnotationZh = config['value']
              }
              if (config['key'] === 'gisNormalAnnotationEn') {
                this.gisNormalAnnotationEn = config['value']
              }
              if (config['key'] === 'gisStatellite') {
                this.gisStatellite = config['value']
              }
              if (config['key'] === 'gisNormal_mapbox') {
                this.gisNormal_mapbox = config['value']
              }
              if (config['key'] === 'gisStatellite_mapbox') {
                this.gisStatellite_mapbox = config['value']
              }
              if (config['key'] === 'gisBoundLeftTop') {
                let cen = config['value']
                let ss = cen.split(',')
                let s1 = ss[0].replace('[', '')
                let s2 = ss[1].replace(']', '').trim()
                this.gisBoundLeftTop = [Number(s1), Number(s2)]
              }
              if (config['key'] === 'gisBoundRightBottom') {
                let cen = config['value']
                let ss = cen.split(',')
                let s1 = ss[0].replace('[', '')
                let s2 = ss[1].replace(']', '').trim()
                this.gisBoundRightBottom = [Number(s1), Number(s2)]
              }
              if (config['key'] === 'gis') {
                this.gis = config['value'] + ''
                // this.gis = 'http://192.168.14.168:7080/PBS/rest/services/MyPBSService/MapServer/tile/{z}/{y}/{x}'
                // let gisNormal = 'http://192.168.14.168:7080/PBS/rest/services/MyPBSService1/MapServer/tile/{z}/{y}/{x}'
                // let gisStatellite = 'http://192.168.14.168:7081/PBS/rest/services/MyPBSService2/MapServer/tile/{z}/{y}/{x}'
                // this.gisNormal = gisNormal
                // this.gisStatellite = gisStatellite
                // this.gis = gisStatellite

                // this.center = [31.22784056, 121.68148040]
                // this.zoom = 12
                // this.minZoom = 12
                // this.maxZoom = 18
              }
            }
            resolve(data.data.data)
          }
        })
      })
    }
  },
  destroy () {
    if (this.polyline) {
      this.polylineGroup.forEach((element) => {
        this.map.removeLayer(element)
      })
    }
    if (this.marker) {
      this.markerGroup.forEach((element) => {
        element.remove()
      })
    }
  }
}
</script>
<style scoped>
#map {
  position: relative;
  width: 100%;
  height: 100%;
}
.openatc-gis >>> .leaflet-container {
    font: 12PX/1.5 "Helvetica Neue", Arial, Helvetica, sans-serif;
    font-size: 12PX;
}
.openatc-gis >>> .leaflet-popup-content {
    font-size: 12PX;
}
</style>
